<template>
	<div class="sales-order-form">
		<el-form
			ref="formRef"
			:model="form"
			:rules="rules"
			label-width="120px"
			@submit.prevent="handleSubmit"
		>
			<!-- 基本信息 -->
			<el-card class="form-card" shadow="never">
				<template #header>
					<div class="card-header">
						<span>基本信息</span>
					</div>
				</template>
				
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="订单主题" prop="orderSubject">
							<el-input v-model="form.orderSubject" placeholder="请输入订单主题" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="订单编号" prop="salesOrderNumber">
							<el-input v-model="form.salesOrderNumber" placeholder="请输入订单编号" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="客户名称" prop="customerName">
							<el-input v-model="form.customerName" placeholder="请输入客户名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="订单日期" prop="salesDate">
							<el-date-picker
								v-model="form.salesDate"
								type="date"
								placeholder="请选择订单日期"
								format="YYYY-MM-DD"
								value-format="YYYY-MM-DD"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="联系人" prop="contactPerson">
							<el-input v-model="form.contactPerson" placeholder="请输入联系人" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系电话" prop="contactPhone">
							<el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="销售部门" prop="departmentId">
							<el-select v-model="form.departmentId" placeholder="请选择销售部门" clearable>
								<el-option
									v-for="dept in departments"
									:key="dept.id"
									:label="dept.name"
									:value="dept.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="销售人员" prop="customerManagerId">
							<el-select v-model="form.customerManagerId" placeholder="请选择销售人员" clearable>
								<el-option
									v-for="person in salespersons"
									:key="person.id"
									:label="person.name"
									:value="person.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="结算方式" prop="settlementMethod">
							<el-select v-model="form.settlementMethod" placeholder="请选择结算方式">
								<el-option label="现金" value="现金" />
								<el-option label="银行转账" value="银行转账" />
								<el-option label="支票" value="支票" />
								<el-option label="信用" value="信用" />
								<el-option label="其他" value="其他" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="关联项目" prop="associatedProjectId">
							<el-select v-model="form.associatedProjectId" placeholder="请选择关联项目" clearable>
								<el-option
									v-for="project in projects"
									:key="project.id"
									:label="project.name"
									:value="project.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="24">
						<el-form-item label="交货地址" prop="deliveryAddress">
							<el-input v-model="form.deliveryAddress" placeholder="请输入交货地址" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="24">
						<el-form-item label="备注" prop="remarks">
							<el-input
								v-model="form.remarks"
								type="textarea"
								:rows="3"
								placeholder="请输入备注信息"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-card>

			<!-- 订单明细 -->
			<el-card class="form-card" shadow="never">
				<template #header>
					<div class="card-header">
						<span>订单明细</span>
						<el-button @click="addDetail" type="primary" size="small" icon="Plus">添加明细</el-button>
					</div>
				</template>

				<el-table :data="form.orderDetails" border stripe>
					<el-table-column type="index" label="#" width="60" />
					<el-table-column label="物品编号" width="150">
						<template #default="{ row, $index }">
							<el-input v-model="row.itemNumber" placeholder="物品编号" />
						</template>
					</el-table-column>
					<el-table-column label="物品名称" width="200">
						<template #default="{ row, $index }">
							<el-input v-model="row.itemName" placeholder="物品名称" />
						</template>
					</el-table-column>
					<el-table-column label="规格型号" width="150">
						<template #default="{ row, $index }">
							<el-input v-model="row.specificationModel" placeholder="规格型号" />
						</template>
					</el-table-column>
					<el-table-column label="单位" width="100">
						<template #default="{ row, $index }">
							<el-input v-model="row.unit" placeholder="单位" />
						</template>
					</el-table-column>
					<el-table-column label="销售数量" width="120">
						<template #default="{ row, $index }">
							<el-input-number
								v-model="row.salesQuantity"
								:min="0.01"
								:precision="2"
								:step="1"
								style="width: 100%"
								@change="calculateAmount($index)"
								placeholder="请输入数量"
							/>
						</template>
					</el-table-column>
					<el-table-column label="含税单价" width="120">
						<template #default="{ row, $index }">
							<el-input-number
								v-model="row.unitPriceIncludingTax"
								:min="0.01"
								:precision="2"
								:step="0.01"
								style="width: 100%"
								@change="calculateAmount($index)"
								placeholder="请输入含税单价"
							/>
						</template>
					</el-table-column>
					<el-table-column label="税率(%)" width="100">
						<template #default="{ row, $index }">
							<el-select v-model="row.taxRate" @change="calculateAmount($index)" style="width: 100%">
								<el-option label="0%" :value="0" />
								<el-option label="3%" :value="3" />
								<el-option label="6%" :value="6" />
								<el-option label="9%" :value="9" />
								<el-option label="13%" :value="13" />
							</el-select>
						</template>
					</el-table-column>
					<el-table-column label="折扣率(%)" width="100">
						<template #default="{ row, $index }">
							<el-input-number
								v-model="row.discountRate"
								:min="0"
								:max="100"
								:precision="2"
								:step="1"
								style="width: 100%"
								@change="calculateAmount($index)"
							/>
						</template>
					</el-table-column>
					<el-table-column label="含税金额" width="120">
						<template #default="{ row }">
							<span>¥{{ formatNumber(row.amountIncludingTax || 0) }}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="100" fixed="right">
						<template #default="{ $index }">
							<el-button @click="removeDetail($index)" type="danger" link icon="Delete">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- 合计信息 -->
				<div class="total-info">
					<el-row :gutter="20">
						<el-col :span="6">
							<span class="total-label">明细数量：</span>
							<span class="total-value">{{ form.orderDetails.length }}</span>
						</el-col>
						<el-col :span="6">
							<span class="total-label">含税总额：</span>
							<span class="total-value">¥{{ formatNumber(totalAmountIncludingTax) }}</span>
						</el-col>
						<el-col :span="6">
							<span class="total-label">不含税总额：</span>
							<span class="total-value">¥{{ formatNumber(totalAmountExcludingTax) }}</span>
						</el-col>
						<el-col :span="6">
							<span class="total-label">税额：</span>
							<span class="total-value">¥{{ formatNumber(totalTaxAmount) }}</span>
						</el-col>
					</el-row>
				</div>
			</el-card>

			<!-- 操作按钮 -->
			<div class="form-actions">
				<el-button @click="handleCancel">取消</el-button>
				<el-button type="primary" @click="handleSubmit" :loading="submitting">
					{{ isEdit ? '更新' : '创建' }}
				</el-button>
			</div>
		</el-form>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type {
	SalesOrderDetailResponse,
	CreateSalesOrderCommand,
	UpdateSalesOrderCommand,
	CreateSalesOrderDetailCommand
} from '@/types/salesOrder'

// Props
interface Props {
	formData: Partial<SalesOrderDetailResponse>
	isEdit: boolean
}

const props = withDefaults(defineProps<Props>(), {
	isEdit: false
})

// Emits
const emit = defineEmits<{
	submit: [data: CreateSalesOrderCommand | UpdateSalesOrderCommand]
	cancel: []
}>()

// Refs
const formRef = ref<FormInstance>()
const submitting = ref(false)

// 表单数据（与后端字段对齐）
const form = reactive({
	orderSubject: '',
	salesOrderNumber: '',
	customerName: '',
	salesDate: '',
	contactPerson: '',
	contactPhone: '',
	departmentId: undefined as number | undefined,
	customerManagerId: undefined as number | undefined,
	settlementMethod: '',
	associatedProjectId: undefined as number | undefined,
	deliveryAddress: '',
	remarks: '',
	orderDetails: [] as any[]
})

// 表单验证规则
const rules: FormRules = {
	orderSubject: [
		{ required: true, message: '请输入订单主题', trigger: 'blur' }
	],
	salesOrderNumber: [
		{ required: true, message: '请输入订单编号', trigger: 'blur' }
	],
	customerName: [
		{ required: true, message: '请输入客户名称', trigger: 'blur' }
	],
	salesDate: [
		{ required: true, message: '请选择订单日期', trigger: 'change' }
	]
}

// 模拟数据（实际项目中应该从API获取）
const customers = ref([
	{ id: 1, name: '客户A' },
	{ id: 2, name: '客户B' },
	{ id: 3, name: '客户C' }
])

const departments = ref([
	{ id: 1, name: '销售部' },
	{ id: 2, name: '市场部' },
	{ id: 3, name: '客服部' }
])

const salespersons = ref([
	{ id: 1, name: '张三' },
	{ id: 2, name: '李四' },
	{ id: 3, name: '王五' }
])

const projects = ref([
	{ id: 1, name: '项目A' },
	{ id: 2, name: '项目B' },
	{ id: 3, name: '项目C' }
])

// 计算属性
const totalAmountIncludingTax = computed(() => {
	return form.orderDetails.reduce((sum: number, d: any) => sum + (d.amountIncludingTax || 0), 0)
})

const totalAmountExcludingTax = computed(() => {
	return form.orderDetails.reduce((sum: number, d: any) => sum + (d.amountExcludingTax || 0), 0)
})

const totalTaxAmount = computed(() => {
	return totalAmountIncludingTax.value - totalAmountExcludingTax.value
})

// 将后端详情映射到表单
const hydrateFormFromDetail = (data: Partial<SalesOrderDetailResponse>) => {
	form.orderSubject = data.orderSubject || ''
	form.salesOrderNumber = data.salesOrderNumber || ''
	form.customerName = data.customerName || ''
	form.salesDate = (data as any).salesDate || ''
	form.contactPerson = data.contactPerson || ''
	form.contactPhone = data.contactPhone || ''
	form.departmentId = (data as any).departmentId as any
	form.customerManagerId = (data as any).customerManagerId as any
	form.settlementMethod = data.settlementMethod || ''
	form.associatedProjectId = (data as any).associatedProjectId as any
	form.deliveryAddress = data.deliveryAddress || ''
	form.remarks = data.remarks || ''
	const details = (data as any).orderDetails || (data as any).details || []
	form.orderDetails = details.map((x: any) => ({
		id: x.id,
		serialNumber: x.serialNumber,
		itemNumber: x.itemNumber,
		itemName: x.itemName,
		specificationModel: x.specificationModel,
		unit: x.unit,
		salesQuantity: x.salesQuantity,
		mainUnitQuantity: x.mainUnitQuantity ?? x.salesQuantity,
		unitPriceIncludingTax: x.unitPriceIncludingTax,
		unitPriceExcludingTax: x.unitPriceExcludingTax ?? 0,
		taxRate: x.taxRate,
		discountRate: x.discountRate,
		amountIncludingTax: x.amountIncludingTax,
		amountExcludingTax: x.amountExcludingTax,
		remarks: x.remarks
	}))
}

// 监听表单数据变化用于反填
watch(() => props.formData, (newData) => {
	if (newData && Object.keys(newData).length > 0) {
		hydrateFormFromDetail(newData)
	}
}, { immediate: true, deep: true })

// 生命周期
onMounted(() => {
	if (!props.isEdit) {
		// 新增时设置默认值
		form.salesDate = new Date().toISOString().split('T')[0]
		form.settlementMethod = '现金'
		form.orderDetails = []
		
		// 生成默认订单编号
		const now = new Date()
		const timestamp = now.getTime()
		const random = Math.floor(Math.random() * 10000)
		form.salesOrderNumber = `SO${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${random}`
	}
})

// 添加明细
const addDetail = () => {
	const newDetail: any = {
		serialNumber: form.orderDetails.length + 1,
		itemNumber: '',
		itemName: '',
		specificationModel: '',
		unit: '',
		salesQuantity: 1,
		mainUnitQuantity: 1,
		taxRate: 13,
		unitPriceIncludingTax: 0.01, // 设置默认最小值为0.01
		unitPriceExcludingTax: 0.01, // 设置默认最小值为0.01
		discountRate: 100,
		amountIncludingTax: 0,
		amountExcludingTax: 0,
		remarks: ''
	}
	form.orderDetails.push(newDetail)
}

// 删除明细
const removeDetail = (index: number) => {
	form.orderDetails.splice(index, 1)
	// 重新编号序号
	form.orderDetails.forEach((d: any, i: number) => d.serialNumber = i + 1)
}

// 计算金额
const calculateAmount = (index: number) => {
	const detail: any = form.orderDetails[index]
	if (detail.salesQuantity && detail.salesQuantity > 0 && detail.unitPriceIncludingTax && detail.unitPriceIncludingTax > 0) {
		// 主单位数量（此处等同销售数量，可根据业务改）
		detail.mainUnitQuantity = Number(detail.salesQuantity)
		// 计算含税金额
		const base = Number(detail.salesQuantity) * Number(detail.unitPriceIncludingTax)
		const discountMultiplier = Number(detail.discountRate || 100) / 100
		detail.amountIncludingTax = base * discountMultiplier
		// 不含税金额
		const taxMultiplier = 1 + Number(detail.taxRate || 0) / 100
		detail.amountExcludingTax = detail.amountIncludingTax / taxMultiplier
		// 不含税单价 - 确保大于0
		detail.unitPriceExcludingTax = Math.max(0.01, Number(detail.unitPriceIncludingTax) / taxMultiplier)
	} else {
		// 重置金额为0
		detail.amountIncludingTax = 0
		detail.amountExcludingTax = 0
		detail.unitPriceExcludingTax = 0
	}
}

// 提交表单
const handleSubmit = async () => {
	if (!formRef.value) return

	try {
		await formRef.value.validate()
		if (form.orderDetails.length === 0) {
			ElMessage.warning('请至少添加一条订单明细')
			return
		}

		// 验证订单明细
		for (let i = 0; i < form.orderDetails.length; i++) {
			const detail = form.orderDetails[i]
			if (!detail.itemNumber || !detail.itemName) {
				ElMessage.warning(`请完善第${i + 1}条明细的物品信息`)
				return
			}
			if (!detail.salesQuantity || detail.salesQuantity <= 0) {
				ElMessage.warning(`第${i + 1}条明细的销售数量必须大于0`)
				return
			}
			if (!detail.unitPriceIncludingTax || detail.unitPriceIncludingTax <= 0) {
				ElMessage.warning(`第${i + 1}条明细的含税单价必须大于0`)
				return
			}
			// 确保不含税单价大于0
			if (!detail.unitPriceExcludingTax || detail.unitPriceExcludingTax <= 0) {
				ElMessage.warning(`第${i + 1}条明细的不含税单价必须大于0`)
				return
			}
		}

		submitting.value = true

		// 重新计算所有明细的金额
		form.orderDetails.forEach((detail: any, index: number) => {
			calculateAmount(index)
		})

		// 构建提交数据（与后端命令对齐）
		const submitData: any = {
			orderSubject: form.orderSubject,
			salesOrderNumber: form.salesOrderNumber,
			isSystemNumber: false,
			customerName: form.customerName,
			contactPhone: form.contactPhone,
			departmentId: form.departmentId,
			associatedProjectId: form.associatedProjectId,
			deliveryAddress: form.deliveryAddress,
			remarks: form.remarks,
			// 修复日期格式：确保使用正确的ISO 8601格式
			salesDate: typeof form.salesDate === 'string' ? 
				form.salesDate + 'T00:00:00.000Z' : 
				new Date(form.salesDate).toISOString(),
			contactPerson: form.contactPerson,
			customerManagerId: form.customerManagerId,
			contactMethod: form.contactPhone,
			settlementMethod: form.settlementMethod,
			orderStatus: '待确认', // 添加订单状态字段
			orderDetails: form.orderDetails.map((d: any) => ({
				id: d.id,
				serialNumber: d.serialNumber,
				itemNumber: d.itemNumber,
				itemName: d.itemName,
				specificationModel: d.specificationModel,
				unit: d.unit,
				salesQuantity: d.salesQuantity,
				mainUnitQuantity: d.mainUnitQuantity ?? d.salesQuantity,
				unitPriceIncludingTax: d.unitPriceIncludingTax,
				unitPriceExcludingTax: d.unitPriceExcludingTax,
				taxRate: d.taxRate,
				discountRate: d.discountRate,
				remarks: d.remarks
			}))
		}

		if (props.isEdit) {
			const updateData = {
				...submitData,
				id: (props.formData as SalesOrderDetailResponse).id
			}
			emit('submit', updateData)
		} else {
			emit('submit', submitData)
		}
	} catch (error) {
		console.error('表单验证失败:', error)
	} finally {
		submitting.value = false
	}
}

// 取消
const handleCancel = () => {
	emit('cancel')
}

// 工具函数
const formatNumber = (num: number) => {
	return Number(num || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
</script>

<style scoped>
.sales-order-form {
	padding: 20px;
}

.form-card {
	margin-bottom: 20px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.total-info {
	margin-top: 20px;
	padding: 16px;
	background-color: #f5f7fa;
	border-radius: 4px;
}

.total-label {
	font-weight: bold;
	color: #606266;
}

.total-value {
	font-size: 16px;
	color: #409eff;
	font-weight: bold;
}

.form-actions {
	display: flex;
	justify-content: center;
	gap: 16px;
	margin-top: 20px;
	padding-top: 20px;
	border-top: 1px solid #ebeef5;
}

::deep(.el-form-item__label) {
	font-weight: 500;
}

::deep(.el-table .el-input),
::deep(.el-table .el-input-number),
::deep(.el-table .el-select) {
	width: 100%;
}
</style> 